package com.example.word.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.word.MyApplication;
import com.example.dict.R;
import com.example.word.adapter.DictAdapter;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Word;
import com.example.word.ui.fragment.HomeFragment;
import com.example.word.util.AlwaysMarqueeTextView;
import com.example.word.util.HttpUtils;
import com.example.word.util.KeyBoardUtil;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 搜索
 */
public class SearchActivity extends AppCompatActivity {
    private ActionBar mTitleBar;//标题栏
    private Activity myActivity;
    private RecyclerView recyclerView;
    private DictAdapter dictAdapter;
    private LinearLayout llEmpty;
    private Boolean mIsAdmin;
    private EditText etQuery;//搜索内容
    private ImageView ivSearch;//搜索图标
    private List<Dict> dictList;
    private String account;
    private AlwaysMarqueeTextView systemMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        myActivity = this;
        recyclerView = findViewById(R.id.rv_dict_list);
        llEmpty = findViewById(R.id.ll_empty);
        etQuery = findViewById(R.id.et_query);
        ivSearch = findViewById(R.id.iv_search);
        systemMsg = findViewById(R.id.systemMsg);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(myActivity, "搜索", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
        }
        //获取控件
        initView();
        //搜索
        ivSearch.setOnClickListener(v -> {
            loadData();//加载数据
        });
        //点击软键盘中的搜索
        etQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                KeyBoardUtil.hideKeyboard(v);//隐藏软键盘
                loadData();//加载数据
                return true;
            }
            return false;
        });

    }

    /**
     * 初始化页面
     */
    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        dictAdapter = new DictAdapter(llEmpty, recyclerView);
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(dictAdapter);
        dictAdapter.setItemListener(new DictAdapter.ItemListener() {
            @Override
            public void ItemClick(Dict dict) {
                boolean isAdmin = (boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
                String account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
                if ("".equals(account)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                } else {//已经登录
                    Intent intent = null;
                    if (isAdmin) {
                        intent = new Intent(myActivity, AddActivity.class);
                        intent.putExtra("dict", dict);
                        startActivityForResult(intent, 100);
                    } else {
                        // 直接查询数据库有多少单词
                        intent = new Intent(myActivity, UnitActivity.class);
                        intent.putExtra("wordCount", dict.getWordNumber());
                        intent.putExtra("dict", dict.getDict());
                        startActivityForResult(intent, 100);
                    }
                }
            }
        });
    }

    private void loadData() {
        if ("".equals(account)) {
            systemMsg.setText(LoginActivity.systemMessage);
        } else {
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getUserStudyPlan", new HashMap<>(), myActivity, StudyPlan.class, response -> {
                // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                StudyPlan studyPlan = response.getData();
                systemMsg.setText(String.format("系统消息: 您今日学习目标为%s个单词，今日已学习%s个单词，累计学习了%s个单词，继续加油噢！", studyPlan.getDayTask(), studyPlan.getTodayCount(), studyPlan.getTotalCount()));
            });
        }
        String content = etQuery.getText().toString();//获取搜索内容
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("dictLike", content);
        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/getDictList", requestParam, myActivity, Dict.class, response -> {
            dictList = response.getDataList();
            if (dictList != null && dictList.size() > 0) {
                recyclerView.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
                dictAdapter.addItem(dictList);
            } else {
                recyclerView.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}
